package com.suncaper.wcss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suncaper.wcss.common.BaseConstant;
import com.suncaper.wcss.common.utls.ExcelUtil;
import com.suncaper.wcss.common.utls.ExcelUtils;
import com.suncaper.wcss.common.utls.StringCastUtils;
import com.suncaper.wcss.model.domain.BatchSetting;
import com.suncaper.wcss.model.domain.Knrd;
import com.suncaper.wcss.model.domain.StudentData;
import com.suncaper.wcss.model.domain.User;
import com.suncaper.wcss.mapper.UserMapper;
import com.suncaper.wcss.model.dto.ExportError;
import com.suncaper.wcss.model.vo.StaVO;
import com.suncaper.wcss.service.BatchSettingService;
import com.suncaper.wcss.service.KnrdService;
import com.suncaper.wcss.service.StudentDataService;
import com.suncaper.wcss.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 学校用户白名单设置 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2021-11-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StudentDataService studentDataService;
    @Autowired
    private BatchSettingService batchSettingService;
    @Autowired
    private KnrdService knrdService;
    @Override
    public User login(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getSn, user.getSn()).eq(User::getName, user.getName());
        User loginUser = baseMapper.selectOne(wrapper);
        if (Objects.isNull(loginUser)) {
            //不管登录的是什么角色，都应该走这套流程
            //-- 判断是不是学校的学生 sn+name
            QueryWrapper<StudentData> studentDataQueryWrapper = new QueryWrapper<>();
            studentDataQueryWrapper.lambda().eq(StudentData::getName,user.getName()).eq(StudentData::getSn,user.getSn());
            StudentData one = studentDataService.getOne(studentDataQueryWrapper);

            if(Objects.nonNull(one)){
                //只有不为null才能进入下一步
                //-- 判断这个学生有没有当前申请批次等级的困难记录 student_id + name+ 困难等级
                BatchSetting batchSetting = batchSettingService.curBatch();
                String level = batchSetting.getDifficultyLevel();//TSKN  BKN  YBKN
                //当前批次的困难级别
                List<String> list = StringCastUtils.levelCast(level);
                QueryWrapper<Knrd> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Knrd::getStudentId,user.getSn()).eq(Knrd::getName,user.getName()).in(Knrd::getPovertyLevel,list);
                List<Knrd> knrds = knrdService.list(queryWrapper);
                //-- 登录成功并添加白名单
                if(knrds.size()>0){
                    User newUser = new User().setName(user.getName()).setSn(user.getSn()).setRoleId(BaseConstant.ROLE_STUDENT);
                    baseMapper.insert(newUser);
                    loginUser = newUser;
                }
            }
        }
        return loginUser;
    }

    @Override
    public void export(HttpServletResponse response, User user) {
        response.setContentType("application/vnd.ms-excel");
        String name = "";
        try {
            name = new String("用户信息表.xls".getBytes("gbk"),"iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment; filename="+name);
        List<User> users = baseMapper.selectList(null);
        try {
            //ExcelUtils.exportUser(users,response);
            ExcelUtil.exportUser(response,users);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Map<String, Object> importUser(MultipartFile file) {
        //这个map表示返回给页面的数据
        Map<String, Object> map = new HashMap<>();
        try {
            //这个map是导入数据验证之后的map
            Map map1 = ExcelUtil.readExcel(file);
            List<ExportError> errors = (List<ExportError>) (map1.get("error"));
            List<String[]> data = (List<String[]>) (map1.get("data"));
            if(errors.size() == 0){
                List<User> insert = new ArrayList<>();
                List<User> update = new ArrayList<>();
                //开始导入
                for(int i=0;i<data.size();i++){

                    QueryWrapper<User> wrapper = new QueryWrapper<>();
                    wrapper.lambda().eq(User::getSn,data.get(i)[0]);
                    User one = super.getOne(wrapper);

                    if(Objects.isNull(one)){
                        one = new User()
                                .setName(data.get(i)[1]).setSn(data.get(i)[0]).setRoleId(Long.valueOf(data.get(i)[2]));
                        insert.add(one);
                    }else {
                        one.setName(data.get(i)[1]).setRoleId(Long.valueOf(data.get(i)[2]));
                        update.add(one);
                    }
                }
                super.saveBatch(insert);
                super.updateBatchById(update);
                map.put("insert",insert.size());
                map.put("update",update.size());
                map.put("status",true);
            }else{
                map.put("status",false);
                map.put("errorMsg","表头格式不正确");
                map.put("errorData",errors);
            }
            //errors:  空的集合
            //data:  有数据（List<String[]>）
        } catch (IOException e) {
            map.put("status",false);
            map.put("errorMsg","文件格式不正确或者文件不存在");
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String,List<StaVO>> staByCollege() {
        Map<String,List<StaVO>> map = new HashMap<>();
        map.put("all",baseMapper.staByCollege());
        map.put("knrd",baseMapper.staKNRDByCollege());
        return map;
    }
}
